
from shutil import which
from os import environ, path as os_path
from configparser import ConfigParser

from .utils import get_user_home


def _get_cxx_from_environ() -> str:
    return environ.get('CXX_COMPILER', None);


def _get_cxx_from_config() -> str:
    conf_path = get_user_home()

    rc = os_path.join(conf_path, '.runcxxrc')
    if not os_path.isfile(rc) or not os_path.exists(rc):
        return None
    
    with open(rc) as f:
        cparser = ConfigParser()
        cparser.read(rc)

        return cparser.get('compiler', 'cxx')
    return None


def _get_cxx_from_shell() -> str:
    return which('g++')


def find_cxx_compiler():
    cxx = _get_cxx_from_environ()
    if cxx: return cxx

    cxx = _get_cxx_from_config()
    if cxx: return cxx

    cxx = _get_cxx_from_shell()
    if cxx: return cxx


def _get_cc_from_environ() -> str:
    return environ.get('C_COMPILER', None);


def _get_cc_from_config() -> str:
    conf_path = get_user_home()

    rc = os_path.join(conf_path, '.runcxxrc')
    if not os_path.isfile(rc) or not os_path.exists(rc):
        return None
    
    with open(rc) as f:
        cparser = ConfigParser()
        cparser.read(rc)

        return cparser.get('compiler', 'c')
    return None


def _get_cc_from_shell() -> str:
    return which('gcc')


def find_cc_compiler():
    cc = _get_cc_from_environ()
    if cc: return cc

    cc = _get_cc_from_config()
    if cc: return cc

    cc = _get_cc_from_shell()
    if cc: return cc
